const User = require('../model/mongo/user.model');
const Role = require('../model/mongo/role.model');

// 获取用户列表
const getUsers = async (ctx) => {
  try {
    const { page = 1, limit = 10, username, status } = ctx.query;
    const query = {};

    if (username) {
      query.username = new RegExp(username, 'i');
    }
    if (status !== undefined) {
      query.status = parseInt(status);
    }

    const users = await User.find(query)
      .select('-password')
      .populate('role')
      .skip((page - 1) * limit)
      .limit(parseInt(limit))
      .sort({ createdAt: -1 });

    const total = await User.countDocuments(query);

    ctx.body = {
      code: 200,
      data: {
        list: users,
        total,
        page: parseInt(page),
        limit: parseInt(limit)
      },
      message: '获取成功'
    };
  } catch (error) {
    ctx.status = 500;
    ctx.body = {
      code: 500,
      message: '服务器错误'
    };
  }
};

// 创建用户
const createUser = async (ctx) => {
  try {
    const { username, password, nickname, email, phone, role, department } = ctx.request.body;

    // 检查用户名是否已存在
    const existingUser = await User.findOne({ username });
    if (existingUser) {
      ctx.status = 400;
      ctx.body = {
        code: 400,
        message: '用户名已存在'
      };
      return;
    }

    // 检查角色是否存在
    const roleExists = await Role.findById(role);
    if (!roleExists) {
      ctx.status = 400;
      ctx.body = {
        code: 400,
        message: '角色不存在'
      };
      return;
    }

    const user = await User.create({
      username,
      password,
      nickname,
      email,
      phone,
      role,
      department,
      status: 1
    });

    ctx.body = {
      code: 200,
      data: user,
      message: '创建成功'
    };
  } catch (error) {
    ctx.status = 500;
    ctx.body = {
      code: 500,
      message: '服务器错误'
    };
  }
};

// 更新用户
const updateUser = async (ctx) => {
  try {
    const { id } = ctx.params;
    const { nickname, email, phone, role, department, status } = ctx.request.body;

    const user = await User.findById(id);
    if (!user) {
      ctx.status = 404;
      ctx.body = {
        code: 404,
        message: '用户不存在'
      };
      return;
    }

    // 如果更新角色，检查角色是否存在
    if (role) {
      const roleExists = await Role.findById(role);
      if (!roleExists) {
        ctx.status = 400;
        ctx.body = {
          code: 400,
          message: '角色不存在'
        };
        return;
      }
    }

    const updatedUser = await User.findByIdAndUpdate(
      id,
      {
        nickname,
        email,
        phone,
        role,
        department,
        status
      },
      { new: true }
    ).select('-password');

    ctx.body = {
      code: 200,
      data: updatedUser,
      message: '更新成功'
    };
  } catch (error) {
    ctx.status = 500;
    ctx.body = {
      code: 500,
      message: '服务器错误'
    };
  }
};

// 删除用户
const deleteUser = async (ctx) => {
  try {
    const { id } = ctx.params;

    const user = await User.findById(id);
    if (!user) {
      ctx.status = 404;
      ctx.body = {
        code: 404,
        message: '用户不存在'
      };
      return;
    }

    await User.findByIdAndDelete(id);

    ctx.body = {
      code: 200,
      message: '删除成功'
    };
  } catch (error) {
    ctx.status = 500;
    ctx.body = {
      code: 500,
      message: '服务器错误'
    };
  }
};

// 重置密码
const resetPassword = async (ctx) => {
  try {
    const { id } = ctx.params;
    const { password } = ctx.request.body;

    const user = await User.findById(id);
    if (!user) {
      ctx.status = 404;
      ctx.body = {
        code: 404,
        message: '用户不存在'
      };
      return;
    }

    user.password = password;
    await user.save();

    ctx.body = {
      code: 200,
      message: '密码重置成功'
    };
  } catch (error) {
    ctx.status = 500;
    ctx.body = {
      code: 500,
      message: '服务器错误'
    };
  }
};

module.exports = {
  getUsers,
  createUser,
  updateUser,
  deleteUser,
  resetPassword
}; 